import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login/index.vue'
import store from '@/store/'
const Home = () => import('@/views/home/index.vue')
const Question = () => import('@/views/question/index.vue')
const Video = () => import('@/views/video/index.vue')
const User = () => import('@/views/user/index.vue')
const Chat = () => import('@/views/user/chat.vue')
const Profile = () => import('@/views/user/profile.vue')
const Article = () => import('@/views/article/index.vue')
const Tabber = () => import('@/components/app-tabbar.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    alias: '/home',
    components: {
      default: Home,
      bottom: Tabber
    }
  },
  {
    path: '/question',
    components: {
      default: Question,
      bottom: Tabber
    }
  },
  {
    path: '/video',
    components: {
      default: Video,
      bottom: Tabber
    },
    meta: {
      isLogin: true
    }
  },
  {
    path: '/user',
    components: {
      default: User,
      bottom: Tabber
    },
    // 添加路由元meta属性
    meta: {
      // 里面添加一个布尔值属性
      isLogin: true
    }
  },
  {
    path: '/user/profile',
    component: Profile
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '/article',
    component: Article
  }
]

const router = new VueRouter({
  routes
})
// const whitePath = ['/video', '/user', '/question']
router.beforeEach((to, from, next) => {
  if (store.getters['user/getToken']) {
    if (to.path.toLowerCase() === 'login') {
      next('/')
    } else {
      next()
    }
  } else {
    // if(to.path.toLowerCase().startsWith('/user')){   // 判断以/user开头的地址
    // 白名单做法  1.定义一个白名单数组  2. 判断
    // if (whitePath.includes(to.path.toLowerCase())) {    // 数组中是否包含跳转地址
    // 路由元做法  1.在路由定义中加入meta对象,里面添加一个布尔值属性
    if (to.meta.isLogin) {
      next('/login')
    } else {
      next()
    }
  }
})

const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return routerPush.call(this, location).catch(error => error)
}

export default router
